//
//  GlobalFunction.h
//  testMessageCenter
//
//  Created by bin.yan on 14-7-22.
//  Copyright (c) 2014年 bin.yan. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <mach/mach_time.h>

static inline UIImage *getColorToImage(UIColor *color){
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

// 使用方法  excuteTime(^{
//       要测试的代码
// });
/// 获取代码执行时间的函数
static inline CGFloat excuteTime (void (^block)(void))
{
    mach_timebase_info_data_t info;
    if (mach_timebase_info(&info) != KERN_SUCCESS)
        return -1.0;
    
    uint64_t start = mach_absolute_time ();
    block ();
    uint64_t end = mach_absolute_time ();
    uint64_t elapsed = end - start;
    
    uint64_t nanos = elapsed * info.numer / info.denom;
    return (CGFloat)nanos / NSEC_PER_SEC;
}

/// 判断字符串是否全部都是空格
static inline BOOL isStrAllSpace(NSString * str)
{
    if ( str == nil )
        return YES;
    
    const char * pstr = str.UTF8String;
    NSInteger n = strlen(pstr);
    NSInteger i = 0;
    
    for (; i < n; i++ )
    {
        if ( (*(pstr + i) != ' ') && (*(pstr + i) != '\n') )
        {
            break;
        }
    }
    
    if (i == n)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

//static inline BOOL isNetworkOk(void)
//{
//    NetworkStatus nStatus = [[Reachability reachabilityWithHostname:@"www.baidu.com"] currentReachabilityStatus];
//    if ( nStatus != NotReachable ) {
//        return YES;
//    }
//#if defined(DEBUG)
//    NSLog(@"www.baidu.com 不可达");
//#endif
//    return NO;
//}
#pragma mark ---将NSDate转实际时间
static inline NSString * dateTurnTimeStr(NSDate * date){
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:date];
    NSDate *localeDate = [date dateByAddingTimeInterval:interval];
    NSDateFormatter * dateFormate = [[NSDateFormatter alloc] init];
    [dateFormate setDateFormat:@"yyyy-MM-dd HH:mm"];
    [dateFormate setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    NSString * cDateStr = [dateFormate stringFromDate:localeDate];
    return cDateStr;
}

static inline BOOL dayEqual(NSString * s, NSString * d)
{
    NSRange range = {0, 10};
    NSString * s_sub = [s substringWithRange:range];
    NSString * d_sub = [d substringWithRange:range];
    
    if ([s_sub isEqualToString:d_sub])
    {
        return YES;
    }
    else
    {
        return NO;
    }
}
/// 把2014-08-04 15:12:39类型的字符串转换成14-08-04
static inline NSString * covnertDateStr(NSString * sourceDataStr)
{
    NSDateFormatter * dateFormate = [[NSDateFormatter alloc] init];
    [dateFormate setDateStyle:NSDateFormatterMediumStyle];
    [dateFormate setTimeStyle:NSDateFormatterShortStyle];
    [dateFormate setDateFormat:@"yyyy-MM-dd HH:mm"];
    
    NSDate * todayDate = [NSDate date];
    NSString * todayString = [dateFormate stringFromDate:todayDate];
    
    NSTimeInterval secondsPerDay = 24 * 60 * 60;
    //今年
    NSString *toYears;
    toYears = [[todayString description] substringToIndex:4];
    
    NSString *dateContent;
    NSDate *currentDate = [dateFormate dateFromString:sourceDataStr];
    NSDate *yesterday = [todayDate dateByAddingTimeInterval: -secondsPerDay];
    NSDate *beforeOfYesterday = [yesterday dateByAddingTimeInterval: -secondsPerDay];
    
    sourceDataStr = [dateFormate stringFromDate:currentDate];
    NSString *dateString = [[sourceDataStr description] substringToIndex:10];
    NSString *dateYears = [[sourceDataStr description] substringToIndex:4];
    [dateFormate setDateFormat:@"yyyy年MM月dd号 HH:mm"];
    NSString *currentdayString = [dateFormate stringFromDate:currentDate];
    NSString *yesterdayString = [[yesterday description] substringToIndex:10];
    NSString *beforeOfYesterdayString = [[beforeOfYesterday description] substringToIndex:10];
    
    
    if ([dateYears isEqualToString:toYears]) {//同一年
        //今 昨 前天的时间
        if ([[[sourceDataStr description] substringToIndex:10] isEqualToString:[[todayString description] substringToIndex:10]]){
            NSTimeInterval late = [currentDate timeIntervalSince1970]*1;
            NSTimeInterval now = [todayDate timeIntervalSince1970]*1;
            NSTimeInterval cha = now - late;
            if (cha/3600 < 1) {
                dateContent = [NSString stringWithFormat:@"%f", cha/60];
                dateContent = [dateContent substringToIndex:dateContent.length-7];
                int num= [dateContent intValue];
                if (num <= 1) {
                    dateContent = [NSString stringWithFormat:@"刚刚"];
                }else{
                    dateContent = [NSString stringWithFormat:@"%@分钟前", dateContent];
                }
            }else{
                NSString *time = [[currentdayString description] substringWithRange:(NSRange){12,5}];
                dateContent = [NSString stringWithFormat:@"今天 %@",time];
            }
            return dateContent;
        } else if ([dateString isEqualToString:yesterdayString]){
            NSString *time = [[currentdayString description] substringWithRange:(NSRange){12,5}];
            dateContent = [NSString stringWithFormat:@"昨天 %@",time];
            return dateContent;
        }else if ([dateString isEqualToString:beforeOfYesterdayString]){
            NSString *time = [[currentdayString description] substringWithRange:(NSRange){12,5}];
            dateContent = [NSString stringWithFormat:@"前天 %@",time];
            return dateContent;
        }else{
            //其他时间
            NSString *time2 = [[currentdayString description] substringWithRange:(NSRange){5,12}];
            return time2;
        }
    }else{
        return [[currentdayString description] substringToIndex:11];
    }
    
    
}

/// 把2014-08-04 15:12:39类型的字符串转换成14-08-04
static inline NSString * timeStamp(NSString * sourceDataStr)
{
    NSDateFormatter * dateFormate = [[NSDateFormatter alloc] init];
    [dateFormate setDateFormat:@"yyyy-MM-dd HH:mm"];
    
    NSDate * currentDate = [NSDate dateWithTimeIntervalSince1970:[sourceDataStr floatValue]];
    NSString * cDateStr = [dateFormate stringFromDate:currentDate];
    
    return cDateStr;
}

static inline NSString* compareDate(float sourceDataStr){
    
    NSTimeInterval secondsPerDay = 24 * 60 * 60;
    
//    //修正8小时之差
    NSDate *date1 = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: date1];
    NSDate *localeDate = [date1  dateByAddingTimeInterval: interval];
    
//    NSLog(@"nowdate=%@\nolddate = %@",localeDate,date);
    NSDate *today = localeDate;
    NSDate *yesterday,*beforeOfYesterday;
    //今年
    NSString *toYears;
    
    toYears = [[today description] substringToIndex:4];
    
    yesterday = [today dateByAddingTimeInterval: -secondsPerDay];
    beforeOfYesterday = [yesterday dateByAddingTimeInterval: -secondsPerDay];
    
    // 10 first characters of description is the calendar date:
    NSString *todayString = [[today description] substringToIndex:10];
    NSString *yesterdayString = [[yesterday description] substringToIndex:10];
    NSString *beforeOfYesterdayString = [[beforeOfYesterday description] substringToIndex:10];
    
    NSDateFormatter * dateFormate = [[NSDateFormatter alloc] init];
    [dateFormate setDateFormat:@"yyyy-MM-dd HH:mm"];
    [dateFormate setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    NSDate * currentDate = [[NSDate dateWithTimeIntervalSince1970:sourceDataStr] dateByAddingTimeInterval: interval];
    NSString * cDateStr = [dateFormate stringFromDate:currentDate];
    
    NSString *dateString = [[cDateStr description] substringToIndex:10];
    NSString *dateYears = [[cDateStr description] substringToIndex:4];
    
    NSString *dateContent;
    if ([dateYears isEqualToString:toYears]) {//同一年
        //今 昨 前天的时间
        if ([dateString isEqualToString:todayString]){
            NSTimeInterval late = [currentDate timeIntervalSince1970]*1;
            NSTimeInterval now = [localeDate timeIntervalSince1970]*1;
            NSTimeInterval cha = now - late;
            if (cha/3600 < 1) {
                dateContent = [NSString stringWithFormat:@"%f", cha/60];
                dateContent = [dateContent substringToIndex:dateContent.length-7];
                int num= [dateContent intValue];
                if (num <= 1) {
                    dateContent = [NSString stringWithFormat:@"刚刚"];
                }else{
                    dateContent = [NSString stringWithFormat:@"%@分钟前", dateContent];
                }
            }else{
                NSString *time = [[cDateStr description] substringWithRange:(NSRange){11,5}];
                dateContent = [NSString stringWithFormat:@"今天 %@",time];
            }
            return dateContent;
        } else if ([dateString isEqualToString:yesterdayString]){
            NSString *time = [[cDateStr description] substringWithRange:(NSRange){11,5}];
            dateContent = [NSString stringWithFormat:@"昨天 %@",time];
            return dateContent;
        }else if ([dateString isEqualToString:beforeOfYesterdayString]){
            NSString *time = [[cDateStr description] substringWithRange:(NSRange){11,5}];
            dateContent = [NSString stringWithFormat:@"前天 %@",time];
            return dateContent;
        }else{
            //其他时间
            NSString *time2 = [[cDateStr description] substringWithRange:(NSRange){5,11}];
            return time2;
        }
    }else{
        return dateString;
    }
}



static inline NSString * getUUID(void)
{
    CFUUIDRef uuidRef = CFUUIDCreate(NULL);
    CFStringRef uuidStringRef =CFUUIDCreateString(NULL, uuidRef);
    CFRelease(uuidRef);
    NSString *uniqueId = (__bridge_transfer NSString *)uuidStringRef;
    return uniqueId;
}

//  获取字符串的大小  ios7
static inline CGSize getStringRectIos7(NSString* aString)
{
    CGSize size;
    UIFont * font = [UIFont boldSystemFontOfSize:13.0f];
    NSDictionary *attributes = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
    
    size = [aString boundingRectWithSize:CGSizeMake(296, 200) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
    
    return  size;
    
}
//  获取字符串的大小  ios6
static inline CGSize getStringRectIos6(NSString* aString)
{
    CGSize size;
    
    UIFont *nameFont=[UIFont boldSystemFontOfSize:13.0f];
    size=[aString sizeWithFont:nameFont constrainedToSize:CGSizeMake(296, 200)lineBreakMode:NSLineBreakByCharWrapping];
    return  size;
}
/// 获取字符串的尺寸
static inline CGSize getStringRect(NSString * aString)
{
    float version = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (version >= 7.0)
    {
        return getStringRectIos7(aString);
    }
    else
    {
        return getStringRectIos6(aString);
    }
}

/// 在界面上显示分享界面
static inline void showFengXiangView(UIViewController * parentVC, UIImage *image, BOOL isShowDeleteBtn, id viewCon, NSString *url, NSString *userName, NSString *content)
{
//    ShareViewViewController * showVVC = [[ShareViewViewController alloc] init];
//    showVVC.isShowDeleteBtn = isShowDeleteBtn;
//    showVVC.image = image;
//    showVVC.url = url;
//    showVVC.content = content;
//    showVVC.userName = userName;
//    showVVC.delegate = viewCon;
//    [parentVC addChildViewController:showVVC];
//    [showVVC didMoveToParentViewController:parentVC];
//    
//    [parentVC.view addSubview:showVVC.view];
}

static inline bool isAChar(char cc)
{
    if ( cc >= 'a' && cc <= 'z' )
        return YES;
    
    if ( cc >= 'A' && cc <= 'Z' )
        return YES;
    
    return NO;
}
static inline bool isANumber(char cc)
{
    if ( cc >= '0' && cc <= '9' )
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

//邮箱
static inline bool isValidEmailAddress(NSString * emailAddress)
{
    if ( nil == emailAddress )
        return NO;
    
    // 判断是否有@
    NSArray * arr = [emailAddress componentsSeparatedByString:@"@"];
    if ( arr.count < 2 )
        return NO;
    
    // 判断@之后是否有.
    NSString * tailStr = [arr lastObject];
    NSArray  * tailArr = [tailStr componentsSeparatedByString:@"."];
    if ( tailArr.count < 2 )
        return NO;
    
    // 判断.前面的是否合法
    const char * p = ( (NSString *)[tailArr firstObject] ).UTF8String;
    NSInteger count = strlen( p );
    if ( 0 == count )
        return NO;
    
    for ( int i = 0; i < count; i++ )
    {
        char c = * ( p + i);
        if ( !isAChar( c ) && !isANumber( c ) )
        {
            return NO;
        }
    }
    
    // 判断前面的字符类型
    p = ( (NSString *)[arr firstObject] ).UTF8String;
    count = strlen( p );
    if ( 0 == count )
        return NO;
    
    for ( int i = 0; i < count; i++ )
    {
        char c = * ( p + i);
        if ( !isAChar( c ) && !isANumber( c ) && c != '_' && c != '.' )
        {
            return NO;
        }
    }
    
    return YES;
}
/// 文件下载库中，创建临时文件路径的函数
static inline NSString * FileDownload_pathOfTempFile(NSString * downloadFilePath)
{
    NSString  *tempDoucment = NSTemporaryDirectory();
    
    NSArray* pathElements = [downloadFilePath componentsSeparatedByString:@"/"];
    NSUInteger count = pathElements.count;
    
    NSString * fileName   = [NSString stringWithFormat:@"%@%@",pathElements[count - 2], pathElements.lastObject];
    
    NSString *tempFilePath = [NSString stringWithFormat:@"%@%@.temp",
                              tempDoucment,
                              fileName];
    
    return tempFilePath;
}

/// 文件下载库中，创建临时文件路径的函数
static inline NSString * FileDownload_pathOfTemp1File(NSString * downloadFilePath)
{
    NSString  *tempDoucment = NSTemporaryDirectory();
    
    NSArray* pathElements = [downloadFilePath componentsSeparatedByString:@"/"];
    NSUInteger count = pathElements.count;
    
    NSString * fileName   = [NSString stringWithFormat:@"%@%@",pathElements[count - 2], pathElements.lastObject];
    
    NSString *tempFilePath = [NSString stringWithFormat:@"%@%@.temp1",
                              tempDoucment,
                              fileName];
    
    return tempFilePath;
}
/// 获取全路径前面的目录
static inline NSString * pathWithoutFileName(NSString * fullPath)
{
    if ( fullPath.length <= 0 ) {
        return nil;
    }
    
    NSRange range = [fullPath rangeOfString:@"/" options:NSBackwardsSearch];
    
    /* 没有找到 */
    if ( range.location == NSNotFound ) {
        return nil;
    }
    
    /* 只包含文件名 */
    if ( range.location == 0 ) {
        return nil;
    }
    
    return [fullPath substringToIndex:range.location];
}

/// 去除url后面的随机后缀
static inline NSString * FileDownload_pathWithoutRandomSuffix(NSString * originalStr)
{
    NSRange range = [originalStr rangeOfString:@"?"];
    if( range.location == NSNotFound )
    {
        return originalStr;
    }
    
    NSRange subStrRange = NSMakeRange(0, range.location);
    return [originalStr substringWithRange:subStrRange];
}

/// 当前系统版本是否超过ios6
static inline BOOL ios6OrLatter(void)
{
    CGFloat systemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
    
    if ( systemVersion >= 6.0f ) {
        return YES;
    } else {
        return NO;
    }
}

///// 图片转编译base64
//static inline NSString* base64StringOfImage(UIImage *image)
//{
//    NSData * jpgeData           = UIImageJPEGRepresentation(image, 0.4f);
//    NSData * base64ImageData    = [GTMBase641 encodeData:jpgeData];
//    
//    NSString * result = [[NSString alloc] initWithData:base64ImageData encoding:NSUTF8StringEncoding];
//    return result;
//}
//
//static inline NSString* base64StringOfPngImage(UIImage *image)
//{
//    NSData * jpgeData           = UIImagePNGRepresentation(image);
//    NSData * base64ImageData    = [GTMBase641 encodeData:jpgeData];
//    
//    NSString * result = [[NSString alloc] initWithData:base64ImageData encoding:NSUTF8StringEncoding];
//    return result;
//}

static inline UILabel *changeLabelAttribute(UILabel *theLab, NSInteger devStart, NSInteger devEnd,UIColor *allColor, UIColor *markColor, float markFontSize){
    NSString *tempStr = theLab.text;
    NSMutableAttributedString *strAtt = [[NSMutableAttributedString alloc] initWithString:tempStr];
    [strAtt addAttribute:NSForegroundColorAttributeName value:allColor range:NSMakeRange(0, [strAtt length])];
    if(devStart > 0){
        devStart = devStart;
    }else{
        devStart = 0;
    }
    NSRange startRange = NSMakeRange(devStart, 0);
    NSRange endRangeOne = NSMakeRange(tempStr.length-devEnd, 1);
    if(startRange.location>=endRangeOne.location){
        [theLab setTextColor:allColor];
        return theLab;
    }
    // 更改字符颜色
    NSRange markRange = NSMakeRange(startRange.location+startRange.length, endRangeOne.location-(startRange.location+startRange.length));
    // 更改字符颜色
    [strAtt addAttribute:NSForegroundColorAttributeName value:markColor range:markRange];
    // 更改字体
    [strAtt addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:markFontSize] range:markRange];
    theLab.attributedText = strAtt;
    return theLab;
}


@interface GlobalFunction : NSObject

@end
